package org.xa3apm.vote.bean;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import org.xa3apm.vote.hibernate.entities.Account;
import org.xa3apm.vote.hibernate.entities.Candidate;
import org.xa3apm.vote.hibernate.entities.Province;
import org.xa3apm.vote.hibernate.entities.Settlement;
import org.xa3apm.vote.hibernate.entities.VoteData;

@Stateless
public class VoteBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5384750717690554239L;
	@PersistenceUnit(unitName = "vote")
	private EntityManagerFactory emf;

	public String getProvinceById(String id) {
		EntityManager em = emf.createEntityManager();
		return ((Province) (em.createNamedQuery("Province.getById")
				.setParameter("id", Long.parseLong(id)).getSingleResult()))
				.getName();
	}

	@SuppressWarnings("unchecked")
	public List<Province> getAll() {
		EntityManager em = emf.createEntityManager();
		return (em.createNamedQuery("Province.getAll")).getResultList();
	}

	public String saveVote(Account account, Candidate candidate, Settlement set) {
		EntityManager em = emf.createEntityManager();
		try {
			VoteData vd = new VoteData(account.hashCode(), candidate,
					set.getName());
			em.persist(vd);
			return "Success";
		} catch (Exception e) {
			// TODO: handle exception
			return "Failed";
		}

	}
}
